package com.dragon.www.smarthome.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.dragon.www.smarthome.R;
import com.dragon.www.smarthome.SHApplication;
import com.dragon.www.smarthome.entity.DeviceInfo;
import com.dragon.www.smarthome.entity.ServiceResult;
import com.dragon.www.smarthome.view.dialog.CProgressDialog;
import com.duowan.mobile.netroid.DefaultRetryPolicy;
import com.duowan.mobile.netroid.NetroidError;
import com.duowan.mobile.netroid.RequestQueue;
import com.duowan.mobile.netroid.request.JsonObjectRequest;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.Map;

/**
 * Created by Administrator on 2015/8/24 0024.
 */
public class NetUtils {
    private static RequestQueue mQueue = Netroid.newRequestQueue(SHApplication.getInstance(), null);

    // POST
    public static void post(final Context context, String postBaseUrl, final Map<String, String> map, final NetCallBack<ServiceResult> callBack, final Class<?> rspCls) {
        if (!isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed("网络未连接");
            return;
        }
        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.NetProcessDialog);
        progressDialog.setMessage("正在获取数据");
        progressDialog.setCancelable(true);
        try {
            if (!progressDialog.isShowing()) {
                progressDialog.show();
            }
        } catch (Exception e) {
        }

        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(postBaseUrl, params, new com.duowan.mobile.netroid.Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                progressDialog.dismiss();
//				int retcode = getRetCode(jsonObject);
//				if (retcode != 0) {
//					if (callBack != null)
//						callBack.failed(context.getResources().getString(R.string.networkerror));
//					return;
//				}
                ServiceResult rsp = null;
                try {
                    Gson gson = new Gson();
                    rsp = (ServiceResult) gson.fromJson(jsonObject.toString(), rspCls);
                } catch (Exception e) {
                    Log.e("NetUtils", "post RspMsgError !");
                    e.printStackTrace();
                }
                if (callBack != null)
                    if (rsp != null) {
                        callBack.success(rsp);
                    } else {
                        callBack.failed("数据解析错误");
                    }
            }

            @Override
            public void onError(NetroidError error) {
                progressDialog.dismiss();
                if (callBack != null)
                    callBack.failed(error.getMessage());
            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(4 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }

    public static void post(final Context context, final String url, final Map<String, Object> map, final String msg, final NetCallBack<ServiceResult> callBack, final Class<?> rspCls) {
        if (!isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed("没有连接网络");
            return;
        }
        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.NetProcessDialog);
        if (msg != null) {
            progressDialog.setMessage(msg);
            progressDialog.setCancelable(true);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {

            }
        }
        JSONObject params = new JSONObject(map);
        Log.e("1请求参数", params.toString());
        JsonObjectRequest request = new JsonObjectRequest( url, params, new com.duowan.mobile.netroid.Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                progressDialog.dismiss();
                ServiceResult rsp = null;
                try {
                    Gson gson = new Gson();
                    Log.e("1成功回调", jsonObject.toString());
                    rsp = (ServiceResult) gson.fromJson(jsonObject.toString(), rspCls);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (callBack != null)
                    if (rsp != null) {
                        callBack.success(rsp);
                    } else {
                        callBack.failed("数据解析错误");
                    }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null) {
                    callBack.failed("网络错误");
                }
                progressDialog.dismiss();
            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(4 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }

    public static void post(final Context context, final String url,JSONObject params, final String msg, final NetCallBack<DeviceInfo> callBack, final Class<?> rspCls) {
        if (!isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed("没有连接网络");
            return;
        }
//        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.NetProcessDialog);
//        if (msg != null) {
//            progressDialog.setMessage(msg);
//            progressDialog.setCancelable(true);
//            try {
//                if (!progressDialog.isShowing()) {
//                    progressDialog.show();
//                }
//            } catch (Exception e) {
//
//            }
//        }
        Log.w("2请求参数", params.toString());
        JsonObjectRequest request = new JsonObjectRequest( url, params, new com.duowan.mobile.netroid.Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
//                progressDialog.dismiss();
                DeviceInfo rsp = null;
                try {
                    Gson gson = new Gson();
                    Log.w("2成功回调", jsonObject.toString());
                    rsp = (DeviceInfo) gson.fromJson(jsonObject.toString(), rspCls);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (callBack != null)
                    if (rsp != null) {
                        callBack.success(rsp);
                    } else {
                        callBack.failed("数据解析错误");
                    }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null) {
                    callBack.failed(error.toString());
                }
//                progressDialog.dismiss();
            }
        });
        request.setRetryPolicy(new DefaultRetryPolicy(4 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }

    public static int getRetCode(JSONObject jsonObject) {
        try {
            return jsonObject.optInt("retcode");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    public interface NetCallBack<T> {
        public void success(T rspData);
        public void failed(String msg);
    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
}
